package iterator;

import java.util.HashSet;
import java.util.Iterator;

public class Iter<T> implements Iterator<T> {
	private Iterator<T> it1;
	private Iterator<T> it2;
	private boolean first = true;

	public Iter() {
		it1 = null;
		it2 = null;
	}

	public Iter(Iterator<T> i1, Iterator<T> i2) throws Exception {
		//D if ( i1.equals(i2)) throw new Exception("Gevalt!");
		it1 = i1;
		it2 = i2;
	}

	@Override
	public boolean hasNext() {
		if (it1 == null || it2 == null)
			return false;
		return (it1.hasNext() || it2.hasNext());
	}

	@Override
	public T next() {
		while (it1.hasNext())
			return it1.next();
		while (it2.hasNext())
			return it2.next();
		return null;
	}

	public T nextB() {
		if ((it1.hasNext() && first) || !it2.hasNext()) {
			first = false;
			return it1.next();
		}
		if ((it2.hasNext() && !first) || !it1.hasNext()) {
			first = true;
			return it2.next();
		}
		return null;
	}

	@Override
	public void remove() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) throws Exception {
		HashSet<Integer> map1 = new HashSet<Integer>();
		HashSet<Integer> map2 = new HashSet<Integer>();
		for (int i = 1; i <= 5; i++)
			map1.add(i);
		for (int i = 6; i <= 8; i++)
			map2.add(i);
		//A
		Iterator<Integer> i1 = map1.iterator();
		Iterator<Integer> i2 = map2.iterator();
		Iter<Integer> iter = new Iter<Integer>(i1, i2);
		while (iter.hasNext())
			System.out.print(iter.next());
		System.out.println();
		//B
		Iterator<Integer> iB1 = map1.iterator();
		Iterator<Integer> iB2 = map2.iterator();
		Iter<Integer> iterB = new Iter<Integer>(iB1, iB2);
		while (iterB.hasNext())
			System.out.print(iterB.nextB());
		System.out.println();
		//C1
		Iterator<Integer> iC1 = map1.iterator();
		Iter<Integer> iterC1 = new Iter<Integer>(iC1, iC1);
		while (iterC1.hasNext())
			System.out.print(iterC1.next());
		System.out.println();
		//C2
		Iterator<Integer> iC2 = map1.iterator();
		Iter<Integer> iterC2 = new Iter<Integer>(iC2, iC2);
		while (iterC2.hasNext())
			System.out.print(iterC2.nextB());
		System.out.println();
	}
}
